package com.sxkiler.demo.seata.service;

import com.sxkiler.demo.seata.dao.ATBusiDao;
import com.sxkiler.demo.seata.dto.BusinessDTO;
import com.sxkiler.demo.seata.dto.OrderDTO;
import com.sxkiler.demo.seata.service.at.ATBusinessService;
import com.sxkiler.demo.seata.service.at.ATOrderService;
import com.sxkiler.demo.seata.service.at.ATProductService;
import com.sxkiler.demo.seata.utils.IDUtils;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ATBusinessServiceImpl implements ATBusinessService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Reference
    ATProductService productService;

    @Reference
    ATOrderService orderService;

    @Autowired
    ATBusiDao atBusiDao;

    @Override
    @GlobalTransactional
    public String handleBusiness(BusinessDTO businessDTO) throws Exception {

        logger.info("[handleBusiness] 开始下单");
        logger.info("[handleBusiness] 当前 XID: {}", RootContext.getXID());

        // 扣减库存
        boolean reduceStock = productService.reduceStock(businessDTO.getProductId(), businessDTO.getCount());

        // 查询 商品单价
        Integer price = productService.getPriceById(businessDTO.getProductId());
        Integer payAmount = price * businessDTO.getCount();

        // 生成订单 ID
        Long orderId = IDUtils.nextId();

        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setId(orderId);
        orderDTO.setUserId(businessDTO.getUserId());
        orderDTO.setProductId(businessDTO.getProductId());
        orderDTO.setCount(businessDTO.getCount());
        orderDTO.setPayAmount(payAmount);
        // 创建订单
        boolean createOrder = orderService.createOrder(orderDTO);

        if(!reduceStock || !createOrder){
            throw new RuntimeException("下单失败");
        }

        logger.info("[handleBusiness] 下单成功, 订单Id: "+ orderId);
        businessDTO.setId(IDUtils.nextId());
        atBusiDao.saveBusi(businessDTO);
        return "Place Order Success";
    }
}
